#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/time.h>
#include<pthread.h>

int calc_sqr(int a){
    sleep(1);
    return a*a;
}

void *thread_func(void *arg){
    int num = *(int *)arg;
    int *result = malloc(sizeof(int));
    *result = calc_sqr(num);

    pthread_exit(result);
}

int main(int argc, char const *argv[])
{
    int item[5] = {1,2,3,4,5};
    int sqrs[5];

    //记时开始
    struct timeval start, end;
    gettimeofday(&start,NULL);
    //计算
    pthread_t pts[5];
    for (int i = 0; i < 5; i++)
    {
        pthread_create(&pts[i],NULL, (void *)thread_func, &item[i]);
    }
    //等代每一个线程结束， 拿到线程的计算结果
    for (int i = 0; i < 5; i++)
    {
        void *result;
        pthread_join(pts[i],&result);
        sqrs[i] = *(int *)result;
    }
    
    //记时结束
    gettimeofday(&end,NULL);

    printf("time = %ld s\n",end.tv_sec - start.tv_sec);

    //求和
    int sum = 0;
    for (int i = 0; i < 5; i++)
    {
        sum += sqrs[i];
    }
    printf("sum = %d",sum);

    return 0;
}


